<template>
	<view class="p-3">
		<wd-form custom-class="rounded-2 overflow-hidden" ref="form" :model="formData">
			<wd-cell-group border>
				<wd-input label="姓名" label-width="100px" prop="name" clearable v-model="formData.name"
					placeholder="请输入姓名"
					:rules="[{ required: true, message: '请填写姓名' }, {pattern:/^(?:[\u4e00-\u9fa5a-zA-Z]){2,}$/,message:'至少两个中文或英文字符'}]" />
				<wd-input label="电话" label-width="100px" prop="phone" clearable v-model="formData.phone"
					placeholder="请输入电话"
					:rules="[{ required: true, message: '请填写电话' },{pattern:/^1[3-9]\d{9}$/,message:'不符合手机号格式'}]" />
				<wd-picker :column-change="onChangeDistrict" :columns="columns" label="地区" v-model="formData.areaCode"
					:rules="[{ required: true, message: '请选择地区' }]" />
				<wd-textarea label="详细地址" label-width="100px" prop="detail" clearable v-model="formData.detail"
					placeholder="请输入详细地址" :rules="[{ required: true, message: '请填写详细地址' }]" />
				<wd-input label="邮政编码" label-width="100px" prop="postcode" clearable v-model="formData.postcode"
					placeholder="请输入邮政编码"
					:rules="[{ required: true, message: '请填写邮政编码' },{pattern:/^[1-9]\d{5}$/,message:'不符合邮政编码格式'}]" />
			</wd-cell-group>
		</wd-form>

		<wd-cell custom-class="rounded-2 overflow-hidden mt-3 mb-5 isDefault" title="设置为默认地址">
			<wd-switch custom-class="translate-y-3px" v-model="formData.isDefault" />
		</wd-cell>

		<wd-button custom-class="mb-3" type="primary" size="large" @click="handleSubmit" block>提交</wd-button>
		<wd-button v-if="id" type="error" size="large" @click="handleDelete" block>删除</wd-button>

	</view>
	<wd-toast />
	<wd-message-box />
</template>

<script setup>
	import {
		areaList
	} from '@vant/area-data';
	import {
		ref
	} from 'vue';
	import {
		createAddress,
		deleteAddress,
		getAddress,
		updateAddress
	} from '../../api/address';
	import {
		useMessage,
		useToast
	} from 'wot-design-uni';
	import {
		onLoad
	} from '@dcloudio/uni-app'

	const {
		province_list,
		city_list,
		county_list
	} = areaList;

	const formData = ref({});
	const columns = ref([
		[],
		[],
		[]
	]);
	const initAreacode = () => {
		const areaCode = formData.value.areaCode;
		const provinceCode = `${areaCode.substring(0, 2)}0000`;
		const cityCode = `${areaCode.substring(0, 4)}00`;
		formData.value.areaCode = [provinceCode, cityCode, areaCode];
		const cityList = [];
		for (const key in city_list) {
			if (key.substring(0, 2) === areaCode.substring(0, 2)) {
				cityList.push({
					label: city_list[key],
					value: key
				})
			}
		}
		console.log(cityList);
		columns.value[1] = cityList;
		const countyList = [];
		for (const key in county_list) {
			console.log(key);
			if (key.substring(0,4) === areaCode.substring(0, 4)){
				countyList.push({
					label: county_list[key],
					value: key
				})
			}
		}
		console.log(countyList);
		columns.value[2] = countyList;
	}


	const id = ref();
	onLoad((e) => {
		id.value = e.id;
		if (e.id) {
			getAddress(id.value).then(res => {
				formData.value = res.data;
				initAreacode();
			});
		}
	});
	const initColumns = () => {
		for (const key in province_list) {
			const value = province_list[key];
			columns.value[0].push({
				label: value,
				value: key
			});
		}
		const initialCityList = [];
		for (const key in city_list) {
			const startWords = key.slice(0, 3);
			if (startWords === '110') columns.value[1].push({
				label: city_list[key],
				value: key
			})
		}
		for (var key in county_list) {
			const startWords = key.slice(0, 4);
			if (startWords === '1101') columns.value[2].push({
				label: county_list[key],
				value: key
			})
		}
		formData.value.areaCode = ["110000", "110100", "110101"];
	}
	initColumns();

	const onChangeDistrict = (a, b, c) => {
		const {
			value
		} = b[c];
		if (c === 0) {
			const provinceStartWords = value.slice(0, 2);
			const cityList = [];
			for (var key in city_list) {
				if (key.startsWith(provinceStartWords)) {
					cityList.push({
						label: city_list[key],
						value: key
					})
				}
			}
			a.setColumnData(1, cityList);
			const firstCity = cityList[0];
			const countyList = [];
			const cityStartWords = firstCity.value.slice(0, 4);
			for (var key in county_list) {
				if (key.startsWith(cityStartWords)) {
					countyList.push({
						label: county_list[key],
						value: key
					})
				}
			}
			a.setColumnData(2, countyList);
		}
		if (c === 1) {
			const startWords = value.slice(0, 4);
			const countList = [];
			for (var key in county_list) {
				if (key.startsWith(startWords)) {
					countList.push({
						label: county_list[key],
						value: key
					})
				}
			}
			a.setColumnData(2, countList);
		}
	}
	const toast = useToast();
	const form = ref();
	const handleBack = () => {
		setTimeout(() => {
			uni.navigateBack();
		}, 1200);
	}
	const handleSubmit = () => {
		form.value.validate().then(async ({
			valid
		}) => {
			if (!valid) return
			const {
				areaCode
			} = formData.value;
			const data = {
				...formData.value,
				areaCode: areaCode[areaCode.length - 1]
			};
			if (id.value) {
				await updateAddress(data)
				toast.success("编辑成功");
			} else {
				await createAddress(data)
				toast.success("创建成功");
			}
			handleBack();
		})
	}

	const message = useMessage();
	const handleDelete = async () => {
		await message.confirm("确认删除吗？");
		await deleteAddress(id.value);
		toast.success("删除成功");
		handleBack();
	}
</script>

<style>
	.isDefault>view {
		display: flex;
		align-items: center;
	}
</style>